/*-----------------------------------------------------------------------------------
Name: Sangyoon Park
Date: January 31 2023
This do file does : 
	Do randomization inference test
-----------------------------------------------------------------------------------*/
clear all
set matsize 10000
set maxvar 30000
set more off
capture log close


#delim ;


/*-----------------------------------------------------------------------------------
			 Set up
-----------------------------------------------------------------------------------*/
*** Setting up files;
	glo datafile "qu_analysis"; 	// type in the name of the datafile that you want to create;
	
*** Setting up folder;
	local RIFolder "${data_path}/RITEST";
	capture mkdir "`RIFolder'"	;

*** Set up program;
 ** Number Format;
	capture program drop autoformat;
	program define autoformat;

	if int(`1')==`1' global format "%12.0f";
	else if abs(`1')>10 global format "%9.1f";
	else if abs(`1')>1 global format "%9.2f";
	else if abs(`1')>.1 global format "%9.3f";
	else if abs(`1')>.01 global format "%9.3f";
	else if abs(`1')>.001 global format "%9.3f";
	else if abs(`1')>.0001 global format "%9.4f";
	else if abs(`1')<.00001 global format "%9.5f";

	end;
	
 ** Tex Table format;
  	capture program drop head_foot;
	program define head_foot;

	syntax, [caption(str)] [label(str)] [notes(str)] [size(str)] [columns(str)] [sideways] [long];

	local estimates=r(names);
	if "`columns'"=="" local columns:word count `estimates';
	if "`sideways'"=="sideways" local table sidewaystable;
	if "`long'"=="long" local table longtable;
	else local table table;
	local col = `columns'+1;

	global header \begin{`table'}[H] \footnotesize \begin{center};
		if "`size'"!="" global header $header \begin{`size'};
		if "`caption'"!="" global header $header \caption{`caption'\label{table:`label'}} ;
		global header $header  ///;
		\begin{adjustbox}{max width=\textwidth} ///;
		\begin{threeparttable} ///;
		\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} ;
		global header $header ///;
		\begin{tabular}{l*{`columns'}{c}}\toprule[1.5pt];

	global header_mid \tabularnewline;

	global panel_title \multicolumn{`col'}{l}{Panel}\tabularnewline \midrule;

	global footer_mid \midrule ;
	global footer \bottomrule[1.2pt] ///
		\end{tabular} ;
		if "`notes'"!="" {;
			global footer $footer \begin{tablenotes}[flushleft] ///;
			`notes' ///;
			\end{tablenotes} ;
			};
		global footer $footer \end{threeparttable}\end{adjustbox};
		if "`size'"!="" global footer $footer \end{`size'};
		global footer $footer \end{center} \end{`table'} 	;
	end;

*** table setting;
	local stat_balance cells("mean(fmt(2)) b(fmt(3) star)" "sd(par fmt(2)) t(par fmt(2))") ///;
			label noobs collabels(none) nonote ;
	local stat_table cells("mean(fmt(2))" "sd(par fmt(2))") label collabels(none) nonote ;

	local reg_table_format cells(b(fmt(3) star) se(par fmt(3))) star(* 0.10 ** 0.05 *** 0.01) ///;
		stats(N r2 ymean, fmt(0 3 2) labels("N" "R-Squared" "Mean of Dep. Var."))  ///;
		label mlabels(none) collabels(none) nonotes;

	local reg_table_format2 cells(b(fmt(3) star) se(par fmt(3))) star(* 0.10 ** 0.05 *** 0.01) ///;
		stats(ymean, fmt(3) labels("Mean of Dep. Var."))  ///;
		label mlabels(none) collabels(none) nonotes;


*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;


/*-----------------------------------------------------------------
                 
				 TABLES IN MAIN TEXT
		  - Randomize once for each treatment
-----------------------------------------------------------------*/

/*
/*-----------------------------------------------------------------
                 Re-randomize Farmer Training
-----------------------------------------------------------------*/;

	local iterate = 5000;
	set seed 1005;

*** Re-randomization treatment groups within strata across clusters;

	preserve;
	keep strata group_id st_tgroup;
	gen farmer_nocert = inlist(st_tgroup, 1,2);
	gen farmer_cert = inlist(st_tgroup, 5,6);
	bys strata group_id: keep if _n == 1;
	forvalues i = 1(1)`iterate' {;
	tempvar randtr rank training;
	gen `randtr' = runiform();
	sort strata farmer_nocert `randtr';
	bys strata farmer_nocert: gen `rank' = _n if farmer_nocert == 1;
	sort strata farmer_cert `randtr';
	bys strata farmer_cert: replace `rank' = _n if farmer_cert == 1;
	gen `training' = (`rank' == 2);
	gen st_tgroup`i' = 1 if `training' == 0 & farmer_nocert == 1;
	replace st_tgroup`i' = 2 if `training' == 1 & farmer_nocert == 1;
	replace st_tgroup`i' = 3 if st_tgroup == 3;
	replace st_tgroup`i' = 4 if st_tgroup == 4;
	replace st_tgroup`i' = 5 if `training' == 0 & farmer_cert == 1;
	replace st_tgroup`i' = 6 if `training' == 1 & farmer_cert == 1;
	replace st_tgroup`i' = 7 if st_tgroup == 7;
	replace st_tgroup`i' = 8 if st_tgroup == 8;

	};
	
	drop farmer_nocert farmer_cert;
	
	keep strata group_id st_tgroup*;
	save "`RIFolder'/RI_FARMERTR_5000", replace;
	
	restore;
	
	
/*-----------------------------------------------------------------
                 Re-randomize Intermediary Training
-----------------------------------------------------------------*/	

*** Re-randomization treatment groups within strata across clusters;
	preserve;
	keep strata group_id st_tgroup;
	gen int_nocert = inlist(st_tgroup, 1,3);
	gen int_cert = inlist(st_tgroup, 5,7);
	bys strata group_id: keep if _n == 1;
	forvalues i = 1(1)`iterate' {;
	tempvar randtr rank training;
	gen `randtr' = runiform();
	sort strata int_nocert `randtr';
	bys strata int_nocert: gen `rank' = _n if int_nocert == 1;
	sort strata int_cert `randtr';
	bys strata int_cert: replace `rank' = _n if int_cert == 1;
	gen `training' = (`rank' == 2);
	gen st_tgroup`i' = 1 if `training' == 0 & int_nocert == 1;
	replace st_tgroup`i' = 2 if st_tgroup == 2;
	replace st_tgroup`i' = 3 if `training' == 1 & int_nocert == 1;
	replace st_tgroup`i' = 4 if st_tgroup == 4;
	replace st_tgroup`i' = 5 if `training' == 0 & int_cert == 1;
	replace st_tgroup`i' = 6 if st_tgroup == 6;
	replace st_tgroup`i' = 7 if `training' == 1 & int_cert == 1;
	replace st_tgroup`i' = 8 if st_tgroup == 8;

	};
	
	drop int_nocert int_cert;
	
	keep strata group_id st_tgroup*;
	save "`RIFolder'/RI_INTTR_5000", replace;
	
	restore;	
	
	
/*-----------------------------------------------------------------
                 Re-randomize Joint Training
-----------------------------------------------------------------*/	

*** Re-randomization treatment groups within strata across clusters;
	preserve;
	keep strata group_id st_tgroup;
	gen joint_nocert = inlist(st_tgroup, 1,4);
	gen joint_cert = inlist(st_tgroup, 5,8);
	bys strata group_id: keep if _n == 1;
	forvalues i = 1(1)`iterate' {;
	tempvar randtr rank training;
	gen `randtr' = runiform();
	sort strata joint_nocert `randtr';
	bys strata joint_nocert: gen `rank' = _n if joint_nocert == 1;
	sort strata joint_cert `randtr';
	bys strata joint_cert: replace `rank' = _n if joint_cert == 1;
	gen `training' = (`rank' == 2);
	gen st_tgroup`i' = 1 if `training' == 0 & joint_nocert == 1;
	replace st_tgroup`i' = 2 if st_tgroup == 2;
	replace st_tgroup`i' = 3 if st_tgroup == 3;
	replace st_tgroup`i' = 4 if `training' == 1 & joint_nocert == 1;
	replace st_tgroup`i' = 5 if `training' == 0 & joint_cert == 1;
	replace st_tgroup`i' = 6 if st_tgroup == 6;
	replace st_tgroup`i' = 7 if st_tgroup == 7;
	replace st_tgroup`i' = 8 if `training' == 1 & joint_cert == 1;

	};
	
	drop joint_nocert joint_cert;
	
	keep strata group_id st_tgroup*;
	save "`RIFolder'/RI_JOINTTR_5000", replace;
	
	restore;	

/*-----------------------------------------------------------------
                 Re-randomize Certification
-----------------------------------------------------------------*/

*** Re-randomization treatment groups within strata across clusters;
	preserve;
	keep strata group_id st_tgroup;
	gen traintr = inlist(st_tgroup, 1,5);
	replace traintr = 2 if inlist(st_tgroup, 2,6);
	replace traintr = 3 if inlist(st_tgroup, 3,7);
	replace traintr = 4 if inlist(st_tgroup, 4,8);
	bys strata group_id: keep if _n == 1;
	forvalues i = 1(1)`iterate' {;
	tempvar randtr rank certif;
	gen `randtr' = runiform();
	sort strata traintr `randtr';
	bys strata traintr: gen `rank' = _n;
	gen `certif' = (`rank' == 2);
	gen st_tgroup`i' = 1 if `certif' == 0 & traintr == 1;
	replace st_tgroup`i' = 2 if `certif' == 0 & traintr == 2;
	replace st_tgroup`i' = 3 if `certif' == 0 & traintr == 3;
	replace st_tgroup`i' = 4 if `certif' == 0 & traintr == 4;
	replace st_tgroup`i' = 5 if `certif' == 1 & traintr == 1;
	replace st_tgroup`i' = 6 if `certif' == 1 & traintr == 2;
	replace st_tgroup`i' = 7 if `certif' == 1 & traintr == 3;
	replace st_tgroup`i' = 8 if `certif' == 1 & traintr == 4;

	};
	
	drop traintr;
	
	keep strata group_id st_tgroup*;
	save "`RIFolder'/RI_CERT_5000", replace;
	
	restore;
*/	
	
/*-----------------------------------------------------------------
                 End of Re-Randomization
-----------------------------------------------------------------*/

	preserve;
	clear;
*** Save game data;
	import excel "${raw_path}/DATA_GAME_ALL.xlsx", sheet("Sheet1") firstrow ;
	tempfile game;
	save `game';
	clear;		
	

*** Save intermediary data;
	use "${data_path}/INTERMEDIARY_LONG.dta", clear;
	rename age firmage;
		egen group_id = group(strata st_tgroup);
		gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
		gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
		gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
		gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
		gen tr_fXcert = tr_farm * certelig;
		gen tr_iXcert = tr_int * certelig;
		gen tr_jXcert = tr_joint * certelig;
		merge m:1 strata group_id using "${data_path}/RITEST/RI_INTTR_5000.dta";
		drop _merge;
	tempfile intdata;
	save `intdata';
	clear;
	restore;

/*-----------------------------------------------------------------
               
			   Estimation for Farmer Training
			   
-----------------------------------------------------------------*/

	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "`RIFolder'/RI_FARMERTR_5000.dta";
	drop _merge;
	tempfile RI_FARMERTR_5000;
	save `RI_FARMERTR_5000';
	
	
/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Farmer GAP" `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_FARMTRAINING", replace;	
	restore;


/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3)
-----------------------------------------------------------------*/	;

	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Farmer Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_FARMTRAINING", replace;	

/*-----------------------------------------------------------------
                Farm Sales (TABLE 4)
-----------------------------------------------------------------*/	;

use `RI_FARMERTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Farmer" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_FARMTRAINING", replace;	

use `RI_FARMERTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Farmer" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_FARMTRAINING", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_FARMERTR_5000.dta";
	drop _merge;
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Farmer" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_FARMTRAINING", replace;	




/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_FARMERTR_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;
	


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		

	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Farmer Training Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_FARMTRAINING", replace;
	
	restore;

	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	

	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Farmer Training Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};						
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_FARMTRAINING", replace;
	
	restore;		
	
/*-----------------------------------------------------------------
               
			   Estimation for Exporter Training
			   
-----------------------------------------------------------------*/

	clear;

*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;




	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "${data_path}/RITEST/RI_INTTR_5000.dta";
	drop _merge;
	tempfile RI_INTTR_5000;
	save `RI_INTTR_5000';
	
/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_tr_int' `ri_tr_farm' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Intermediary GAP" `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' tr_int tr_farm tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_INTTRAINING", replace;	
	restore;


/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3)
-----------------------------------------------------------------*/	
	
	clear;
	use `RI_INTTR_5000';
	
	
	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_int' `ri_tr_farm' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Intermediary Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_int tr_farm tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_INTTRAINING", replace;	


/*-----------------------------------------------------------------
                Farm Sales (TABLE 4)
-----------------------------------------------------------------*/	;

clear;

use `RI_INTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_int' `ri_tr_farm' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Farmer" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_int tr_farm  tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exportertraining assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_INTTRAINING", replace;	
clear;
use `RI_INTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_int' `ri_tr_farm' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Farmer" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_int tr_farm tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_INTTRAINING", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_INTTR_5000.dta";
	drop _merge;
	tempfile RI_INTTR_5000;
	save `RI_INTTR_5000';
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_int' `ri_tr_farm' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Intermediary" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_int tr_farm tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_INTTRAINING", replace;	

	


/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_INTTR_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


*gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		


	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_int' `ri_tr_farm'  `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Intermediary training Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare tr_int tr_farm  tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_INTTRAINING", replace;
	
	restore;
	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_int' `ri_tr_farm'  `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Intermediary Training Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};		
	
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare tr_int tr_farm  tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_INTTRAINING", replace;
	
	restore;	

	
/*-----------------------------------------------------------------
               
			   Estimation for Joint Training
			   
-----------------------------------------------------------------*/

	clear;

*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;




	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "${data_path}/RITEST/RI_JOINTTR_5000.dta";
	drop _merge;	
	tempfile RI_JOINTTR_5000;
	save `RI_JOINTTR_5000';
	
/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Joint GAP" `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' tr_joint tr_int tr_farm certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_JOINTTRAINING", replace;	
	restore;
	

/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3)
-----------------------------------------------------------------*/	

	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_joint' `ri_tr_farm' `ri_tr_int' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Joint Training Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_joint tr_farm tr_int certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_JOINTTRAINING", replace;	
	clear;
	

/*-----------------------------------------------------------------
                Farm Sales (TABLE 4)
-----------------------------------------------------------------*/	;

clear;

use `RI_JOINTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Joint Training Farm Sales" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_joint tr_int tr_farm certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_JOINTTRAINING", replace;	
clear;

use `RI_JOINTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Joint Training Farm Sales" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_joint tr_int tr_farm certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_JOINTTRAINING", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_JOINTTR_5000.dta";
	drop _merge;
	tempfile RI_JOINTTR_5000;
	save `RI_JOINTTR_5000';
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Joint Training" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_joint tr_int tr_farm certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating joint training assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_JOINTTRAINING", replace;	
	


/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_JOINTTR_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;	

** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


*gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		

	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_joint' `ri_tr_farm' `ri_tr_int'  `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Joint Training Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare tr_joint tr_farm tr_int certelig tr_fXcert tr_iXcert tr_jXcert `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on game residue outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_JOINTTRAINING", replace;
	
	restore;
	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_joint' `ri_tr_farm' `ri_tr_int' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Joint Training Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};		
	
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare tr_joint tr_farm tr_int  certelig tr_fXcert tr_iXcert tr_jXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	

		
	
	label data "This file contains results from permutating joint training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_JOINTTRAINING", replace;
	
	restore;	

	
/*-----------------------------------------------------------------
               
			   Estimation for Certification
			   
-----------------------------------------------------------------*/
	
	clear;

*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;


	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "${data_path}/RITEST/RI_CERT_5000.dta";
	drop _merge;	
	tempfile RI_CERT_5000;
	save `RI_CERT_5000';
	

/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Cert GAP" `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' certelig tr_joint tr_int tr_farm tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_CERTELIG", replace;	
	restore;


/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3);
-----------------------------------------------------------------*/	

	clear;
	use `RI_CERT_5000';
	
	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_certelig' `ri_tr_joint' `ri_tr_farm' `ri_tr_int' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Certification Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' certelig tr_joint tr_farm tr_int tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating certification assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_CERTELIG", replace;	
	clear;
	
/*-----------------------------------------------------------------
                Farm Sales (TABLE 4);
-----------------------------------------------------------------*/	

clear;

use `RI_CERT_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Certification Farm Sales" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' certelig tr_joint tr_int tr_farm tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating certification assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_CERTELIG", replace;	
clear;

use `RI_CERT_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Certification Farm Sales" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' certelig tr_joint tr_int tr_farm tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating certification assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_CERTELIG", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_CERT_5000.dta";
	drop _merge;
	tempfile RI_CERT_5000;
	save `RI_CERT_5000';
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Certification" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' certelig tr_joint tr_int tr_farm tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating certification assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_CERTELIG", replace;	
	
*/

/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_CERT_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;
	


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		

	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_certelig' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Certification Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare certelig tr_farm tr_int tr_joint tr_fXcert tr_iXcert tr_jXcert `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating certification assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_CERTELIG", replace;
	
	restore;
	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_certelig' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Certification Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};		
	
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare certelig tr_farm tr_int tr_joint  tr_fXcert tr_iXcert tr_jXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating certification assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_CERTELIG", replace;
	
	restore;	
	
	
/*-----------------------------------------------------------------
               
   Estimation for Farmer Training * Certificate Eligibility
			   
-----------------------------------------------------------------*/;

	clear;

*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;




	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "${data_path}/RITEST/RI_FARMERTR_5000.dta";
	drop _merge;
	tempfile RI_FARMERTR_5000;
	save `RI_FARMERTR_5000';
	
	
/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_tr_fXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Farmer and Cert GAP " `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' tr_fXcert tr_farm tr_int tr_joint certelig tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_FARMTRAININGXCERT", replace;	
	restore;	

/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3)
-----------------------------------------------------------------*/	

	clear;
	use `RI_FARMERTR_5000';
	
	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_farm' `ri_tr_int' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Farmer and Cert Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_fXcert certelig tr_joint tr_farm tr_int tr_iXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_FARMTRAININGXCERT", replace;	
	clear;
	

/*-----------------------------------------------------------------
                Farm Sales (TABLE 4);
-----------------------------------------------------------------*/	

clear;

use `RI_FARMERTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y'  `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Farm and Cert Farm Sales" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_fXcert certelig tr_joint tr_int tr_farm tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_FARMTRAININGXCERT", replace;	
clear;

use `RI_FARMERTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Farm and Cert Farm Sales" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_fXcert certelig tr_joint tr_int tr_farm tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_FARMTRAININGXCERT", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_FARMERTR_5000.dta";
	drop _merge;
	tempfile RI_FARMERTR_5000;
	save `RI_FARMERTR_5000';
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_iXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Farm and Cert" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_fXcert certelig tr_joint tr_int tr_farm tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_FARMTRAININGXCERT", replace;	
	

/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_FARMERTR_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		

	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_fXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig'  `ri_tr_iXcert' `ri_tr_jXcert' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Farmer and Certification Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare tr_fXcert tr_farm tr_int tr_joint certelig  tr_iXcert tr_jXcert `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_FARMTRAININGXCERT", replace;
	
	restore;
	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_fXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig'  `ri_tr_iXcert' `ri_tr_jXcert' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Farmer and Certification Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};		
	
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare tr_fXcert tr_farm tr_int tr_joint certelig  tr_iXcert tr_jXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_FARMTRAININGXCERT", replace;
	
	restore;	

	
/*-----------------------------------------------------------------
               
		Estimation for Intermediary Training * Certificate Eligibility
			   
-----------------------------------------------------------------*/
	
	clear;

*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;



	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "${data_path}/RITEST/RI_INTTR_5000.dta";
	drop _merge;	
	tempfile RI_INTTR_5000;
	save `RI_INTTR_5000';
	
/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_tr_iXcert' `ri_tr_int' `ri_tr_farm' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Intermediary and Cert GAP " `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' tr_iXcert tr_int tr_farm tr_joint certelig tr_fXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_INTTRAININGXCERT", replace;	
	restore;

/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3)
-----------------------------------------------------------------*/	

	clear;
	use `RI_INTTR_5000';
	
	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_iXcert' `ri_certelig' `ri_tr_joint' `ri_tr_farm' `ri_tr_int' `ri_tr_fXcert' `ri_tr_jXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Int and Cert Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_iXcert certelig tr_joint tr_farm tr_int tr_fXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_INTTRAININGXCERT", replace;	
	clear;


/*-----------------------------------------------------------------
                Farm Sales (TABLE 4);
-----------------------------------------------------------------*/	

clear;

use `RI_INTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_iXcert' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Int and Cert Farm Sales" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_iXcert tr_fXcert certelig tr_joint tr_int tr_farm tr_jXcert `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_INTTRAININGXCERT", replace;	
clear;

use `RI_INTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_iXcert' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_jXcert' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Int and Cert Farm Sales" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y'  tr_iXcert tr_fXcert certelig tr_joint tr_int tr_farm tr_jXcert `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_INTTRAININGXCERT", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_INTTR_5000.dta";
	drop _merge;
	tempfile RI_INTTR_5000;
	save `RI_INTTR_5000';
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'  `ri_tr_iXcert' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_tr_jXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Int and Cert" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_iXcert tr_fXcert certelig tr_joint tr_int tr_farm tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_INTTRAININGXCERT", replace;	
	
*/

/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_INTTR_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;
	


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		


	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_iXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert'  `ri_tr_jXcert' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Intermediary and Certification Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare tr_iXcert tr_farm tr_int tr_joint certelig tr_fXcert  tr_jXcert `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_INTTRAININGXCERT", replace;
	
	restore;
	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_iXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert'  `ri_tr_jXcert' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Intermediary and Certification Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};		
	
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare tr_iXcert tr_farm tr_int tr_joint certelig tr_fXcert  tr_jXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating exporter training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_INTTRAININGXCERT", replace;
	
	restore;	

	
/*-----------------------------------------------------------------
               
			 Estimation for Joint Training * Certificate Eligibility
			   
-----------------------------------------------------------------*/
	
	clear;

*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;


	local iterate = 5000;
	set seed 1005;
	merge m:1 strata group_id using "${data_path}/RITEST/RI_JOINTTR_5000.dta";
	drop _merge;	
	tempfile RI_JOINTTR_5000;
	save `RI_JOINTTR_5000';
	
/*-----------------------------------------------------------------
                 GAP Compliance (TABLE 2)
-----------------------------------------------------------------*/

	preserve;
	local outcome "score pestman equipman hygman landman fertman";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' `ri_tr_jXcert' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Joint and Cert GAP" `i';	
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg std_`y' tr_jXcert tr_joint tr_int tr_farm certelig tr_fXcert tr_iXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating farmer training assignment 5000 times on GAP compliance outcomes"; 
	save "${data_path}/RITEST/GAP_JOINTTRAININGXCERT", replace;	
	restore;

/*-----------------------------------------------------------------
                Pesticide Residue (TABLE 3)
-----------------------------------------------------------------*/	
	
	clear;
	use `RI_JOINTTR_5000';
	
	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_jXcert' `ri_tr_iXcert' `ri_certelig' `ri_tr_joint' `ri_tr_farm' `ri_tr_int' `ri_tr_fXcert' `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Joint and Cert Pesticide" `i';
	drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_jXcert tr_iXcert certelig tr_joint tr_farm tr_int tr_fXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on pesticide residue outcomes"; 
	save "`RIFolder'/PESTICIDEEU_JOINTTRAININGXCERT", replace;	
	clear;
	

/*-----------------------------------------------------------------
                Farm Sales (TABLE 4);
-----------------------------------------------------------------*/	

clear;

use `RI_JOINTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';

	
*** Round 1;	
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y' `ri_tr_jXcert' `ri_tr_iXcert' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Joint and Cert Farm Sales" `i' "Round" 1;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 1;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_jXcert tr_iXcert tr_fXcert certelig tr_joint tr_int tr_farm `balance' `intbalance' i.strata if round==1, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};

	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R1_JOINTTRAININGXCERT", replace;	
clear;

use `RI_JOINTTR_5000';

set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;

*** Round 2;	
	local outcome "log_price log_totalvolume revenue imp_revenue profit imp_profit";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 10 | _n > _N-10;	
	
	qui reg `y'  `ri_tr_jXcert' `ri_tr_iXcert' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	disp "Joint and Cert Farm Sales" `i' "Round" 2;	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';

	};
	
	local p = 1;
	
	foreach y of local outcome {;
		preserve;
		qui keep if round == 2;
		sort `y' randnum;
		qui drop if _n <= 5 | _n > _N-5;	
	
	qui reg `y' tr_jXcert tr_iXcert tr_fXcert certelig tr_joint tr_int tr_farm `balance' `intbalance' i.strata if round==2, robust cluster(group_id);
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	restore;	
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on farm business outcomes"; 
	save "`RIFolder'/FARMSALES_R2_JOINTTRAININGXCERT", replace;		


/*-----------------------------------------------------------------
                Contract Trade (TABLE 6);
-----------------------------------------------------------------*/	

	clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;
	drop if round == 0;
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);
	
*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;	
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;		
	
	merge m:1 strata group_id using "${data_path}/RITEST/RI_JOINTTR_5000.dta";
	drop _merge;
	tempfile RI_JOINTTR_5000;
	save `RI_JOINTTR_5000';
	
	
	local outcome "progmeet spot_within spot_outside contract_within contract_outside";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' `ri_tr_jXcert' `ri_tr_iXcert' `ri_tr_fXcert' `ri_certelig' `ri_tr_joint' `ri_tr_int' `ri_tr_farm' `balance' `intbalance' i.strata i.round, robust cluster(group_id); 	
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`i',`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	disp "Joint and Cert" " Contract " `i';	
	qui drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
	};
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y' tr_jXcert tr_iXcert tr_fXcert certelig tr_joint tr_int tr_farm `balance' `intbalance' i.strata i.round, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};	
	
	
	label data "This file contains results from permutating joint training assignment `iterate' times on Buyer Contract"; 
	save "`RIFolder'/CONTRACT_JOINTTRAININGXCERT", replace;	
	


/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (TABLE 5)
-----------------------------------------------------------------------------------*/

** Merge with intermediary data;	
	use `RI_JOINTTR_5000';
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;


local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;


gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;

local int_balance firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0;
		

	preserve;
	keep if farmer == 1;

	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';
	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_jXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert'  `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Joint and Certification Farmer Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};			
	
	local p = 1;
	foreach y of local outcome {;	
	
	qui reg `y'_partnershare tr_jXcert tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert  `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 
	mat B = e(b);
	forvalues j = 1(1)1 {;
	local q = `j'*`p';
	mat BB[`iterate'+1,`q'] = B[1,`j'];
	};
	local p = `p'+1;
	};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/FARMER_PARTNERSHARE_JOINTTRAININGXCERT", replace;
	
	restore;
	
	preserve;
	keep if farmer == 0;
	
	local outcome "g2 g3 g1";
	local count_outcome = `:word count `outcome'';
	mat BB = J(`iterate'+1,`count_outcome',0);
	forvalues i = 1(1)`iterate' {;
	tempvar ri_tr_farm ri_tr_int ri_tr_joint ri_certelig ri_tr_fXcert ri_tr_iXcert ri_tr_jXcert;
	gen `ri_tr_farm' = (st_tgroup`i' == 2 | st_tgroup`i' == 6);
	gen `ri_tr_int' = (st_tgroup`i' == 3 | st_tgroup`i' == 7);
	gen `ri_tr_joint' = (st_tgroup`i' == 4 | st_tgroup`i' == 8);
	gen `ri_certelig' = (st_tgroup`i' == 5 | st_tgroup`i' == 6 | st_tgroup`i' == 7 | st_tgroup`i' == 8);
	gen `ri_tr_fXcert' = `ri_tr_farm' * `ri_certelig';
	gen `ri_tr_iXcert' = `ri_tr_int' * `ri_certelig';
	gen `ri_tr_jXcert' = `ri_tr_joint' * `ri_certelig';	
	
	local p = 1;
	foreach y of local outcome {;

		qui reg `y'_partnershare `ri_tr_jXcert' `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert'  `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`i',`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
		disp "Joint and Certification Intermediary Game" `i';
		drop `ri_tr_farm' `ri_tr_int' `ri_tr_joint' `ri_certelig' `ri_tr_fXcert' `ri_tr_iXcert' `ri_tr_jXcert';
		};		
	
	
	local p = 1;
	foreach y of local outcome {;	
	
		qui reg `y'_partnershare tr_jXcert tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 
		mat B = e(b);
		forvalues j = 1(1)1 {;
		local q = `j'*`p';
		mat BB[`iterate'+1,`q'] = B[1,`j'];
		};
		local p = `p'+1;
		};
	
	svmat BB, names(coefficients);
	keep coefficients*;
	keep if coefficients1 != .;
	gen experiment = (_n == `iterate'+1);
	forvalues i = 1(1) `count_outcome'{;
		gen exper_coef`i' = coefficients`i' if experiment == 1;
		egen exp_coef`i' = mean(exper_coef`i');
		sort experiment coefficients`i';
		bys experiment: gen rank`i' = _n/`iterate';
		gen pval`i' = rank`i' if coefficients`i' < exp_coef`i';
		bys experiment: egen max_pval`i' = max(pval`i');
		replace max_pval`i' = 1-max_pval`i';
		local depvar: word `i' of `outcome';
		rename max_pval`i' pval_`depvar';
		};
	
	label data "This file contains results from permutating joint training assignment `iterate' times on game outcomes"; 
	save "`RIFolder'/INT_PARTNERSHARE_JOINTTRAININGXCERT", replace;
	
	restore;	

	clear;

/*-----------------------------------------------------------------
                 
		APPEND ALL RANDOMIZATION INFERENCE OUTCOMES
	
-----------------------------------------------------------------*/	
	
	local treatment "FARMTRAINING INTTRAINING JOINTTRAINING CERTELIG FARMTRAININGXCERT INTTRAININGXCERT JOINTTRAININGXCERT";
	local outcome "GAP PESTICIDEEU FARMSALES_R1 FARMSALES_R2 CONTRACT ";
	
	local i = 1;
	foreach x of local outcome {;
	foreach y of local treatment {;
		use "${data_path}/RITEST/`x'_`y'.dta";
		
		keep pval_*;
		keep if _n == 1;
		
		tempfile `x'_`y';
		save ``x'_`y'';
		clear;
	};
	};
	
	local treatment "INTTRAINING JOINTTRAINING CERTELIG FARMTRAININGXCERT INTTRAININGXCERT JOINTTRAININGXCERT";	
	
	foreach x of local outcome {; 
		use ``x'_FARMTRAINING';
		foreach y of local treatment {;
			append using ``x'_`y'', force;
		};
		
		foreach z of varlist _all {;
	
		replace `z' = 1 - `z' if `z'>0.5 & `z' !=.;
		replace `z' = `z'*2 if `z' !=.;
		
		};		
		
		tempfile `x'_RIPVALUE;
		save ``x'_RIPVALUE';
		
	};

************** GAME OUTCOMES ***********;

	local treatment "FARMTRAINING INTTRAINING JOINTTRAINING CERTELIG FARMTRAININGXCERT INTTRAININGXCERT JOINTTRAININGXCERT";
	local outcome "FARMER_PAR";
	
	local i = 1;
	foreach x of local outcome {;
	foreach y of local treatment {;
		use "${data_path}/RITEST/`x'TNERSHARE_`y'.dta";
		
		keep pval_*;
		keep if _n == 1;
		
		rename pval_g1 pval_g1_farmer;
		rename pval_g2 pval_g2_farmer;
		rename pval_g3 pval_g3_farmer;
		
		tempfile `x'_`y';
		save ``x'_`y'';
		clear;
	};
	};
	
	local outcome "INT_PAR";
	
	local i = 1;
	foreach x of local outcome {;
	foreach y of local treatment {;
		use "${data_path}/RITEST/`x'TNERSHARE_`y'.dta";
		
		keep pval_*;
		keep if _n == 1;
		
		rename pval_g1 pval_g1_int;
		rename pval_g2 pval_g2_int;
		rename pval_g3 pval_g3_int;
		
		tempfile `x'_`y';
		save ``x'_`y'';
		clear;
	};
	};	
	
	local treatment "INTTRAINING JOINTTRAINING CERTELIG FARMTRAININGXCERT INTTRAININGXCERT JOINTTRAININGXCERT";	
	local outcome "FARMER_PAR INT_PAR";
	
	foreach x of local outcome {; 
		use ``x'_FARMTRAINING';
		foreach y of local treatment {;
			append using ``x'_`y'', force;
		};
		
		foreach z of varlist _all {;
	
		replace `z' = 1 - `z' if `z'>0.5 & `z' !=.;
		replace `z' = `z'*2 if `z' !=.;
		
		};		
		
		tempfile `x'TNERSHARE_RIPVALUE;
		save ``x'TNERSHARE_RIPVALUE';
		
	};	

	use `FARMER_PARTNERSHARE_RIPVALUE';
	append using `INT_PARTNERSHARE_RIPVALUE';
	order pval_g1_farmer pval_g1_int pval_g2_farmer pval_g2_int pval_g3_farmer pval_g3_int;
	tempfile GAME_RIPVALUE;
	save `GAME_RIPVALUE';
	

*** APPEND ALL PVALUES;	
	local outcome "PESTICIDEEU FARMSALES_R1 FARMSALES_R2 GAME CONTRACT";
	use `GAP_RIPVALUE';

	foreach x of local outcome {;
		append using ``x'_RIPVALUE';
		
	};	
	
	save "${data_path}/RITEST/ALL_RIPVALUE.dta", replace;
	
